package com.zang.schema.observable.ring;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 观察者：观察目标
 *
 * 铃 具体事物 事件源 目标
 * 触发事件
 * @author Zhang Qiang
 * @Date 2019/8/29 16:37
 */
public class RingSource {
    /**
     * 监听器容器
     */
    private static List<EventListener> listeners ;

    static {
        listeners = new ArrayList<>();
    }

    /**
     * 监听器
     */
    public boolean addListener(EventListener listener){
        return listeners.add(listener);
    }
    public boolean removeListener(EventListener listener){
        return listeners.remove(listener);
    }

    /**
     * 事件
     */
    public void ringEvent(boolean sound){
        String type = sound ? "上课" : "下课";
        System.out.println(type);
        RingEvent ringEvent = new RingEvent(this, sound);
        notifies(ringEvent);
    }

    /**
     * 通知方法
     * 通知所有监听器
     */
    public void notifies(RingEvent ringEvent){
        EventListener eventListener = null;
        Iterator<EventListener> iterator = listeners.iterator();
        while (iterator.hasNext()){
            eventListener = iterator.next();
            eventListener.heardBell(ringEvent);
        }
    }


}
